﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Clipboard.Tools.FileIcon
{
    public class FileIconHelper
    {
        // 定义 SHGetFileInfo 函数，调用 Windows API 获取图标
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(
            string pszPath,
            uint dwFileAttributes,
            ref SHFILEINFO psfi,
            uint cbFileInfo,
            uint uFlags);

        // 定义 SHFILEINFO 结构
        [StructLayout(LayoutKind.Sequential)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }

        // 定义 SHGFI 标志
        private const uint SHGFI_ICON = 0x000000100;
        private const uint SHGFI_SMALLICON = 0x000000001;
        private const uint SHGFI_LARGEICON = 0x000000000;
        private const uint SHGFI_FOLDER = 0x00000002;  // 特别用于文件夹
        private const uint SHGFI_SYSICONINDEX = 0x000004000;  // 获取系统图标索引
        private const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute

        // 获取文件或文件夹的图标
        public static Icon GetFileOrFolderIcon(string path)
        {
            SHFILEINFO shFileInfo = new SHFILEINFO();
            //uint flags = SHGFI_ICON | SHGFI_LARGEICON;

            uint flags = SHGFI_ICON | SHGFI_LARGEICON;

            // 判断是否为文件夹，若是文件夹使用文件夹图标
            if (Directory.Exists(path))
            {
                flags |= SHGFI_FOLDER;
            }

            //SHGetFileInfo(path, 0, ref shFileInfo, (uint)Marshal.SizeOf(shFileInfo), flags);

            SHGetFileInfo(path, 0, ref shFileInfo, (uint)Marshal.SizeOf(shFileInfo), flags | SHGFI_SYSICONINDEX);

            // 返回图标
            if (shFileInfo.hIcon != IntPtr.Zero)
            {
                return Icon.FromHandle(shFileInfo.hIcon);
            }
            else
            {
                // 返回一个默认图标
                return SystemIcons.Information;
            }
        }
    }
}

